package leetcode.剑指offer.剑指II;

import leetcode.剑指offer.pojo.ListNode;
import org.junit.Test;

import java.util.*;

/**
 * @author ：zsy
 * @date ：Created 2021/8/7 17:31
 * @description：https://leetcode-cn.com/problems/middle-of-the-linked-list/
 */
public class 链表的中间结点 {
    @Test
    public void test() {
        Solution solution = new Solution();
        ListNode head = new ListNode(1,
                new ListNode(2,
                        new ListNode(3,
                                new ListNode(4))));
        System.out.println(solution.middleNode(head).val);
    }

    class Solution {
        public ListNode middleNode(ListNode head) {
            // 快慢指针
            ListNode slow = head;
            ListNode fast = head;
            while (fast.next != null && fast.next.next != null) {
                slow = slow.next;
                fast = fast.next.next;
            }
            return fast.next == null ? slow : slow.next;
        }
    }

}
